package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import model.Company;
import model.Race;
import service.CompanyService;
import service.RaceService;
import service.impl.CompanyServiceImpl;
import service.impl.RaceServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

/**
 * @Author: 燕子豪
 * @Date: 2022/12/18 11:13
 */
@WebServlet("/companyListByName")
public class CompanyListByNameServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        CompanyService companyService = new CompanyServiceImpl();
        //解析前端并转为json类型
        BufferedReader reader = new BufferedReader(request.getReader());
        StringBuilder json = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            json.append(line);
        }
        JSONObject jsonObject = JSON.parseObject(json.toString());

        //解析前端的参数：partName、pageIndex，pageSize给定为5
        String partName = jsonObject.getString("partName");
        int pageIndex = Integer.parseInt(jsonObject.getString("pageIndex"));
        List<Company> companies = companyService.selectByName(partName,pageIndex,5);
        int count = companyService.countByName(partName);

        //将数据List打包为json发给前端
        JSONObject message = new JSONObject();
        message.put("companiesMsg",companies);
        message.put("countMsg",count);
        response.getWriter().write(message.toString());
    }
}
